package com.wuyangnju.lj.simulation.master.model;

import java.util.concurrent.locks.ReentrantLock;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.wuyangnju.lj.simulation.master.model.snapshot.PlanDataSnapshot;

public class PlanData {
	private static final Log log = LogFactory.getLog(PlanData.class);

	private double sum = 0;
	private double sumOfSquares = 0;
	private long count = 0;
	private double fixedVar = 0;
	private final ReentrantLock lock = new ReentrantLock(true);

	public long addDateItem(double dataItem) {
		lock.lock();
		try {
			sum += dataItem;
			sumOfSquares += Math.pow(dataItem, 2);
			count++;
			return (count - 1);
		} catch (Exception e) {
			log.error("add data item fail", e);
		} finally {
			lock.unlock();
		}
		return -3;
	}

	public double getFixedVar() {
		return fixedVar;
	}

	public void setFixedVar() {
		fixedVar = (new PlanDataSnapshot(sum, sumOfSquares, count)).var_S2();
	}

	public PlanDataSnapshot snapshot() {
		return new PlanDataSnapshot(sum, sumOfSquares, count, fixedVar);
	}
}
